<template>
    <div class="system-department-container">
        <el-form :inline="true" ref="form" class="system-search-form" :model="searchForm">
            <el-form-item>
                <el-cascader
                    class="go-out"
                    v-model="searchForm.mechanism"
                    :options="mechanismList"
                    :show-all-levels="false"
                    :props="{ checkStrictly: true, emitPath: false }"
                    filterable
                    size="small">
                </el-cascader>
            </el-form-item>
            <el-form-item>
                <el-input type="text" v-model="searchForm.name" maxlength="100" placeholder="科室编码、科室名称" @keyup.enter.native="toFirstPage()" size="small"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button class="sub-btn" type="primary" size="small" @click="toFirstPage()">查询</el-button>
            </el-form-item>
        </el-form>
        <div class="table-box">
            <el-button class="add-btn" type="primary" icon="el-icon-plus" size="small" v-auth="{code: 300004000001}" @click="showAddDialog">新增科室</el-button>
            <el-button class="add-btn" type="warning" icon="el-icon-upload" size="small" v-auth="{code: 300004000001}" @click="showUploadDialog">批量导入</el-button>
            <el-table
                ref="tableData"
                :data="tableData"
                tooltip-effect="light"
                border
                :max-height="tableHeight"
                @sort-change="sortChange"
                class="data-table">
                <el-table-column
                    label="序号"
                    align="center"
                    type="index"
                    width="50">
                </el-table-column>
                <el-table-column
                    prop="code"
                    align="center"
                    label="院内科室编码"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="name"
                    align="center"
                    label="院内科室名称"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="standardDepartment"
                    align="center"
                    label="标准科室编码"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{scope.row.standardDepartment.length ? scope.row.standardDepartment[0].code : ''}}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="standardDepartment"
                    align="center"
                    label="标准科室名称"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{scope.row.standardDepartment.length ? scope.row.standardDepartment[0].name : ''}}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="createdName"
                    label="创建人"
                    align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="createdTime"
                    label="创建时间"
                    align="center"
                    sortable="custom"
                    show-overflow-tooltip
                    width="160">
                </el-table-column>
                <el-table-column
                    label="启/停"
                    align="center"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.state" size="small" :disabled="!showBtnAuth(300004000002)" @change="toChangeState(scope.$index, scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    align="center"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-button type="text" size="small" v-auth="{code: 300004000002}" @click="tableEdit(scope.$index, scope.row)">
                            编辑
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableData.length > 0" :total="total" :page.sync="currentPage" :limit.sync="pageSize"
                        @pagination="getData"/>
        </div>
        <el-dialog
            :title="isAdd ? '新增科室' : '编辑科室'"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            @close="closeDialog"
            center
            width="40%">
            <el-form :inline="true" ref="dialogForm" class="dialog-form" :rules="editFormRules" :model="editForm" label-width="110px">
                <el-form-item label="机构" prop="mechanism">
                    <el-cascader
                        class="go-out"
                        v-model="editForm.mechanism"
                        :options="mechanismList"
                        :show-all-levels="false"
                        :props="{ checkStrictly: true, emitPath: false }"
                        filterable
                        size="small">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="启/停" class="switch-box">
                    <el-switch v-model="editForm.status"></el-switch>
                </el-form-item>
                <el-form-item label="院内科室编码" prop="code">
                    <el-input type="text" maxlength="100" v-model="editForm.code" placeholder="请输入科室编码" size="small"></el-input>
                </el-form-item>
                <el-form-item label="院内科室名称" prop="name">
                    <el-input type="text" maxlength="100" v-model="editForm.name" placeholder="请输入科室名称" size="small"></el-input>
                </el-form-item>
                <el-form-item label="标准科室编码" prop="normalCode">
                    <el-select v-model="editForm.normalCode" filterable placeholder="请选择科室编码" size="small" @change="changeCode">
                        <el-option
                            v-for="item in standardDep"
                            :key="item.code"
                            :label="item.code"
                            :value="item.code">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标准科室名称" prop="normalName">
                    <el-select v-model="editForm.normalName" filterable placeholder="请选择科室名称" size="small" @change="changeName">
                        <el-option
                            v-for="item in standardDep"
                            :key="item.code"
                            :label="item.newName"
                            :value="item.code">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog" size="small">取 消</el-button>
                <el-button type="primary" @click="submitEditForm('dialogForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            title="批量导入科室"
            :visible.sync="dialogVisibleUpload"
            :close-on-click-modal="false"
            custom-class="uploadDialog"
            width="30%"
            center
            :before-close="handleClose">
            <div class="content">
                <div class="top-content">
                    <el-cascader
                        class="go-out"
                        v-model="uploadMechanism"
                        :options="mechanismList"
                        :show-all-levels="false"
                        :props="{ checkStrictly: true, emitPath: false }"
                        filterable
                        size="small">
                    </el-cascader>
                    <el-button type="text" @click="downloadTemplate">下载模板</el-button>
                </div>
                <upload-file
                    :drag="true"
                    :limit="limit"
                    accept=".xls,.xlsx"
                    :noPrompt="true"
                    :fileList="fileList"
                    @removeFile="removeFile">
                </upload-file>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose" size="small">取 消</el-button>
                <el-button type="primary" @click="submitFileList" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {getDepartmentList, addDepartment, editDepartment, changeState, uploadDepartmentFile, getStandardDep} from '@/api/system/department'
    import {showBtnAuth, getSortString} from '@/utils/filters'
    import Pagination from '@/components/Pagination'
    import uploadFile from '@/components/Upload'

    export default {
        name: 'index',
        data () {
            return {
                // 搜索表单
                searchForm: {
                    mechanism: '',
                    name: ''
                },
                // 机构列表
                mechanismList: [],
                // 表格数据
                tableData: [],
                // 数据总数
                total: 0,
                // 当前页
                currentPage: 1,
                // 每页数量
                pageSize: 10,
                // 表格高度
                tableHeight: 100,
                // 显示弹框
                dialogVisible: false,
                // 弹框表单
                editForm: {
                    mechanism: '',
                    code: '',
                    name: '',
                    status: true,
                    normalCode: '',
                    normalName: ''
                },
                // 是否是新增
                isAdd: true,
                // 导入科室文件
                fileList: [],
                // 最大上传数量
                limit: 1,
                // 显示上传弹框
                dialogVisibleUpload: false,
                // 上传机构id
                uploadMechanism: '',
                // 排序字段
                sortMap: {},
                // 排序方式
                sortType: '',
                // 初次默认用户机构（可用/判断过是否存在）
                defaultMId: '',
                // 标准科室列表
                standardDep: [],
                editFormRules: {
                    mechanism: [
                        {required: true, message: '请选择机构', trigger: 'change'}
                    ],
                    code: [
                        {required: true, message: '请填写科室编码', trigger: ['blur', 'change']}
                    ],
                    name: [
                        {required: true, message: '请填写科室名称', trigger: ['blur', 'change']}
                    ],
                    normalCode: [
                        {required: true, message: '请选择科室编码', trigger: ['blur', 'change']}
                    ],
                    normalName: [
                        {required: true, message: '请选择科室名称', trigger: ['blur', 'change']}
                    ]
                },
                // 使用储存的数据，不去请求
                useStoreList: false,
                useStoreStandard: false
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStoreList = this.$route.query.tags === 'tags'
            this.useStoreStandard = this.$route.query.tags === 'tags'
            let height = document.documentElement.clientHeight - 213 - 10 - 78 - 5
            this.tableHeight = height > 107 ? height : 107
            this.getMechanismList()
            this.getStandardDepList()
            this.initData()
            this.getData()
        },
        mounted () {
            window.onresize = () => {
                // 213=其他元素高度60+50+48+55 10=距离底部边距 78=分页组件高度 5=适应性调整
                let height = document.documentElement.clientHeight - 213 - 10 - 78 - 5
                this.tableHeight = height > 107 ? height : 107
            }
        },
        methods: {
            showBtnAuth,
            /**
             * 初始化页面参数
             */
            initData () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (JSON.stringify(query) !== '{}') {
                    this.searchForm.mechanism = query.orgId
                    this.searchForm.name = query.keyword
                    this.currentPage = query.index || 1
                    this.pageSize = query.pageSize || 10
                    this.sortType = query.orderBy || null
                }
            },
            /**
             * 获取标准科室列表
             */
            getStandardDepList () {
                if (this.getSession(this.$route.name, 'getStandardDep') && this.useStoreStandard) {
                    this.useStoreStandard = false
                    let res = this.getSession(this.$route.name, 'getStandardDep')
                    if (res.code.toString() === '200') {
                        this.standardDep = res.data
                        this.initDepList()
                    }
                } else {
                    getStandardDep().then(res => {
                        this.useStoreStandard = false
                        this.setSession(this.$route.name, {getStandardDep: res})
                        if (res.code.toString() === '200') {
                            this.standardDep = res.data
                            this.initDepList()
                        }
                    })
                }
            },
            /**
             * 处理标准科室重复名称
             */
            initDepList () {
                let repeatName = this.getRepeatDep()
                this.standardDep.forEach(item => {
                    if (repeatName.includes(item.name) && item.sid) {
                        item.newName = `${item.name}(${this.getParentDep(item.sid)})`
                    } else {
                        item.newName = item.name
                    }
                })
            },
            /**
             * 获取重复名称科室
             */
            getRepeatDep () {
                let allName = this.standardDep.map((item) => { return item.name })
                let tmp = []
                if (Array.isArray(allName)) {
                    allName.concat().sort().sort((a, b) => {
                        if (a === b && tmp.indexOf(a) === -1) tmp.push(a)
                    })
                }
                return tmp
            },
            /**
             * 获取父级科室
             */
            getParentDep (sid) {
                let res = this.standardDep.filter(item => item.id === sid)
                return res.length ? res[0].name : ''
            },
            /**
             * 修改标准科室编码
             */
            changeCode (val) {
                this.editForm.normalName = val
            },
            /**
             * 修改标准科室名称
             */
            changeName (val) {
                this.editForm.normalCode = val
            },
            /**
             * 获取机构列表
             */
            getMechanismList () {
                let mechanismList = this.getLocalStorage('userInfo', 'mechanism')
                let parentList = []
                mechanismList.forEach(item => {
                    // 一级机构
                    if (!item.pid) {
                        parentList.push({
                            value: item.id,
                            label: item.name,
                            children: []
                        })
                        // 有一级机构的二级机构
                        mechanismList.forEach(it => {
                            if (it.pid === item.id) {
                                parentList[parentList.length - 1].children.push({
                                    value: it.id,
                                    label: it.name,
                                    children: null
                                })
                            }
                        })
                        if (!parentList[parentList.length - 1].children.length) {
                            parentList[parentList.length - 1].children = null
                        }
                    } else {
                        // 二级机构
                        let parent = mechanismList.filter(i => item.pid === i.id)
                        if (!parent.length) {
                            parentList.push({
                                value: item.id,
                                label: item.name,
                                children: null
                            })
                        }
                    }
                })
                this.mechanismList = parentList
                if (this.mechanismList.length) {
                    if (this.getLocalStorage('userMechanism', 'id') && this.hasMechanismId(this.getLocalStorage('userMechanism', 'id'))) {
                        this.searchForm.mechanism = this.getLocalStorage('userMechanism', 'id')
                    } else {
                        this.searchForm.mechanism = parentList[0].value
                    }
                }
                this.defaultMId = this.searchForm.mechanism
            },
            /**
             * 判断所属机构是否在组织机构中
             * @param id 所属机构id
             */
            hasMechanismId (id) {
                let res = this.mechanismList.filter(item => item.value === id)
                return res.length !== 0
            },
            /**
             * 修改条件后从第一页开始
             */
            toFirstPage () {
                this.currentPage = 1
                this.getData()
            },
            /**
             * 获取表格数据
             * @param type 是否重置页码
             */
            getData (type) {
                this.defaultMId = this.searchForm.mechanism
                let params = {
                    orgId: this.searchForm.mechanism,
                    keyword: this.searchForm.name,
                    index: this.currentPage,
                    pageSize: this.pageSize
                }
                if (this.sortType) params.orderBy = this.sortType
                this.setGetStore(this.$route.name, params)
                if (this.getSession(this.$route.name, 'getDepartmentList') && this.useStoreList) {
                    this.useStoreList = false
                    let res = this.getSession(this.$route.name, 'getDepartmentList')
                    if (res.code.toString() === '200') {
                        this.tableData = res.data.rows
                        this.sortMap = res.data.maps
                        this.total = res.data.total
                    }
                } else {
                    getDepartmentList(params).then(res => {
                        this.useStoreList = false
                        this.setSession(this.$route.name, {getDepartmentList: res})
                        if (res.code.toString() === '200') {
                            this.tableData = res.data.rows
                            this.sortMap = res.data.maps
                            this.total = res.data.total
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            },
            /**
             * 排序修改
             * @param colData.prop 排序参数
             * @param colData.order 正序倒序 ascending 升序 descending 降序 null 不排序默认
             */
            sortChange (colData) {
                this.sortType = getSortString(colData, this.sortMap)
                this.tableData = []
                this.currentPage = 1
                this.getData()
            },
            /**
             * 启动停止
             * @param index 索引
             * @param row 行数据
             */
            toChangeState (index, row) {
                let text = ''
                let title = ''
                if (row.state) {
                    text = `您确定启用"${row.name}"科室吗?`
                    title = '启用科室'
                } else {
                    text = `您确定停用"${row.name}"科室吗?停用后将影响该科室数据统计，请谨慎操作!`
                    title = '停用科室'
                }
                this.$confirm(text, title, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    this.changeIdState(row.id, row.state)
                }).catch(() => {
                    row.state = !row.state
                })
            },
            /**
             * 改变指定状态
             * @param id 数据id
             * @param state 状态
             */
            changeIdState (id, state) {
                let params = {
                    id: id,
                    isEnable: state
                }
                changeState(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$message.success(state ? '启用成功' : '停用成功')
                        this.$store.dispatch('user/getUserInfoAgain')
                    } else if (res.code.toString() === '404') {
                        this.$message.error('未找到该职务')
                    } else {
                        this.$message.error(res.message)
                    }
                    this.getData()
                })
            },
            /**
             * 编辑表格内容
             * @param index 索引
             * @param row 行数据
             */
            tableEdit (index, row) {
                this.isAdd = false
                this.editForm = {
                    mechanism: row.organizationId,
                    code: row.code,
                    name: row.name,
                    status: row.state,
                    id: row.id,
                    normalCode: row.standardDepartment && row.standardDepartment.length ? row.standardDepartment[0].code : '',
                    normalName: row.standardDepartment && row.standardDepartment.length ? row.standardDepartment[0].code : ''
                }
                this.dialogVisible = true
            },
            /**
             * 关闭弹框
             */
            closeDialog () {
                this.editForm = {
                    mechanism: '',
                    code: '',
                    name: '',
                    status: true,
                    normalCode: '',
                    normalName: ''
                }
                this.$refs['dialogForm'].resetFields()
                this.dialogVisible = false
            },
            /**
             * 点击新增打开弹窗
             */
            showAddDialog () {
                this.isAdd = true
                this.editForm.mechanism = this.defaultMId
                this.dialogVisible = true
            },
            /**
             * 提交弹框表单
             * @param formName 表单名
             */
            submitEditForm (formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let name = this.standardDep.filter(item => item.code === this.editForm.normalName)[0].name
                        let params = {
                            organizationId: this.editForm.mechanism,
                            name: this.editForm.name,
                            code: this.editForm.code,
                            state: this.editForm.status,
                            standardDepartment: [{
                                code: this.editForm.normalCode,
                                name: name
                            }]
                        }
                        if (this.isAdd) {
                            addDepartment(params).then(res => {
                                if (res.code.toString() === '200') {
                                    this.$message.success('新增成功')
                                    this.$store.dispatch('user/getUserInfoAgain')
                                    this.closeDialog()
                                    this.getData()
                                } else {
                                    this.$message.error(res.message)
                                }
                            })
                        } else {
                            params.id = this.editForm.id
                            editDepartment(params).then(res => {
                                if (res.code.toString() === '200') {
                                    this.$message.success('保存成功')
                                    this.$store.dispatch('user/getUserInfoAgain')
                                    this.closeDialog()
                                    this.getData()
                                } else {
                                    this.$message.error(res.message)
                                }
                            })
                        }
                    } else {
                        return false
                    }
                })
            },
            /**
             * 关闭前
             */
            handleClose () {
                if (this.fileList.length > 0) {
                    this.$confirm('还未上传，是否关闭？')
                        .then(() => {
                            this.closeDialogUpload()
                        })
                        .catch(() => {})
                } else {
                    this.closeDialogUpload()
                }
            },
            /**
             * 关闭上传弹框
             */
            closeDialogUpload () {
                this.fileList = []
                this.dialogVisibleUpload = false
            },
            /**
             * 打开上传弹框
             */
            showUploadDialog () {
                this.fileList = []
                this.uploadMechanism = this.defaultMId
                this.dialogVisibleUpload = true
            },
            /**
             * 删除文件
             * @param uid 要删除的文件
             */
            removeFile (uid) {
                let index = this.fileList.findIndex(item => {
                    return item.uid === uid
                })
                if (index !== -1) {
                    this.fileList.splice(index, 1)
                }
            },
            /**
             * 提交上传文件
             */
            submitFileList () {
                if (this.fileList.length === 0) {
                    this.$message.warning('请先上传文件')
                    return false
                } else if (this.uploadMechanism === '') {
                    this.$message.warning('请先选择机构')
                    return false
                } else {
                    let form = new FormData()
                    for (let i = 0; i < this.fileList.length; i++) {
                        form.append('file', this.fileList[i].raw, this.fileList[i].raw.name)
                    }
                    form.append('id', this.uploadMechanism)
                    uploadDepartmentFile(form).then(res => {
                        if (res.code.toString() === '200') {
                            this.$message.success('上传成功')
                            this.getData()
                            this.closeDialogUpload()
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            },
            /**
             * 下载模板
             */
            downloadTemplate () {
                this.downloadTemplateData('批量导入科室模板示例')
            },
            /**
             * 下载模板
             * @param val 文件名
             */
            downloadTemplateData (val) {
                let aLink = document.createElement('a')
                aLink.download = val
                aLink.href = `/mrms/static/${val}.xlsx`
                document.body.appendChild(aLink)
                aLink.click()
                document.body.removeChild(aLink)
            }
        },
        components: {
            Pagination,
            uploadFile
        },
        beforeDestroy () {
            window.onresize = null
        }
    }
</script>

<style lang="scss" scoped>
    .system-department-container {
        .system-search-form {
            .el-form-item {
                margin-bottom: 0;
            }
        }
        .table-box {
            background: #fff;
            padding: 10px;
            box-sizing: border-box;
            height: calc(100vh - 183px);
            .add-btn {
                margin-bottom: 10px;
            }
        }
        /deep/.el-dialog {
            width: 800px!important;
            .el-dialog__body {
                padding: 10px;
                .dialog-form {
                    width: 90%;
                    margin: 0 auto;
                    .el-form-item {
                        width: 48%;
                        .el-input {
                            width: 200px;
                        }
                    }
                }
            }
            .el-dialog__footer {
                text-align: right;
            }
            &.uploadDialog {
                width: 30vw!important;
                .top-content {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 10px;
                }
            }
        }
    }
</style>
